/*
 * File Name : groups.cpp
 * Auther : dream.liuguobiao
 * Create Date : 2010-5-11
 * Last Edit : 2010-5-14
 */
#include "groups.h"

groups *groups::instance_groups = NULL;

groups::groups()
:first_group(NULL),last_group(NULL),new_ID(0),group_count(0)
{
}

groups *groups::get_groups(){
  if( 0 == instance_groups){
    instance_groups = new groups();
  }
  return instance_groups;
}

group *groups::find_group_by_name( std::string *name ){
  group *tmp_group = first_group;
  for( ; NULL != tmp_group ; tmp_group = tmp_group->get_next_group() ){
    if ( *( tmp_group->get_name() ) == *name )
      return tmp_group;
  }
  return NULL;
}

group *groups::find_group_by_ID( int ID ){
  group *tmp_group = first_group;
  for( ; NULL != tmp_group ; tmp_group = tmp_group->get_next_group() ){
    if (  tmp_group->get_ID() == ID )
      return tmp_group;
  }
  return NULL;
}

bool groups::delete_group_by_name( std::string *name ){
  group *tmp_group = first_group;
  group *previouse_group;
  for( ; NULL != tmp_group ; tmp_group = tmp_group->get_next_group() ){
    if ( *( tmp_group->get_name() ) == *name ){
      if( first_group == last_group && last_group == tmp_group ){
        first_group = last_group = NULL;
      }else {
        previouse_group->set_next_group( tmp_group->get_next_group() );
      }
      delete tmp_group;
      group_count -- ;
      return 0;
    }
    previouse_group = tmp_group;
  }
  return 1;
}

bool groups::insert_group( group *new_group ){
  group *tmp_group = first_group;
  for( ; NULL != tmp_group ; tmp_group = tmp_group->get_next_group() ){
    if ( *( tmp_group->get_name() ) == *(new_group->get_name() ) )
      return 1;
  }
  if( NULL == last_group ){
    first_group = last_group = new_group ;
  }else {
    last_group->set_next_group( new_group );
    last_group = new_group;
  }
  new_group->set_ID( new_ID ++ );
  group_count++;
  return 0;
}

int groups::get_group_count(){
  return group_count;
}

